package com.example.springboot.controller;

import com.example.springboot.pojo.Result;
import com.example.springboot.pojo.User;
import com.example.springboot.pojo.Worker;
import com.example.springboot.service.UserService;
import com.example.springboot.service.ValidationService;
import com.example.springboot.service.WorkerService;
import com.example.springboot.util.Encrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/updatePassword")
public class UpdatePasswordController {
    @Autowired
    private UserService userService;
    @Autowired
    private WorkerService workerService;
    @Autowired
    private ValidationService validationService;


    @PutMapping("/")
    public Result<?> updatePassword(String type,String email,String code,String password){
        if(type.equals("user")){
            User u = userService.findByEmail(email);
            if(u == null){
                return Result.error("不存在的邮箱，请查证后重试");
            }else{
                if(validationService.checkValidation(email,code)){
                    userService.updatePassword(email, Encrypt.toMD5(password));
                    return Result.success();
                }else{
                    return Result.error("验证码错误！");
                }
            }
        } else if (type.equals("worker")) {
            Worker w = workerService.findByEmail(email);
            if(w == null){
                return Result.error("不存在的账号，请查证后重试");
            }else{
                if(validationService.checkValidation(email,code)){
                    workerService.updatePassword(email,Encrypt.toMD5(password));
                    return Result.success();
                }else{
                    return Result.error("验证码错误！");
                }
            }
        }else{
            return Result.error("不支持的用户类型");
        }
    }
}
